#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Timestamp.h"
#include <time.h>

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        printf("argc error!\n");
        return -1;
    }

    int sockfd;
    struct sockaddr_in servaddr;
    char buf[1024];


    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("socket() failed.\n");
        return -1;
    }

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(atoi(argv[2]));
    servaddr.sin_addr.s_addr = inet_addr(argv[1]);

    if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0)
    {
        printf("connect(%s:%s) failed.\n", argv[1], argv[2]);
        close(sockfd);
        return -1;
    }

    // printf("connect ok.\n");
    printf("开始:%s\n", Timestamp::now().toString().c_str());
    for(int idx = 0; idx < 100000; idx++)
    {
        memset(buf, 0, sizeof(buf));
        sprintf(buf, "这是第%d次fuckYou", idx);

        char tmpbuf[1024];              //报文头部+报文内容
        memset(tmpbuf, 0, sizeof(tmpbuf));
        int len = strlen(buf);          //计算报文大小
        memcpy(tmpbuf, &len, 4);        //报文头部
        memcpy(tmpbuf + 4, buf, len);   //拼接报文内容
        if(send(sockfd, tmpbuf, len + 4, 0) <= 0)
        {
            printf("write() failed.\n");
            close(sockfd);
            return -1;
        }
    // }

    // for(int idx = 0; idx < 1; idx++)
    // {
        //int len;
        recv(sockfd, &len, 4, 0);

        memset(buf, 0, sizeof(buf));
        if(recv(sockfd, buf, len, 0) <= 0)
        {
            printf("read() failed.\n");
            close(sockfd);
            return -1;
        }

        // printf("recv:%s\n", buf);
    }
    printf("结束:%s\n", Timestamp::now().toString().c_str());
    return 0;
}